<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="版本号" prop="versionNum">
        <el-input
          v-model="queryParams.versionNum"
          placeholder="请输入版本号模糊查询"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="图纸号" prop="drawNum">
        <el-input
          v-model="queryParams.drawNum"
          placeholder="请输入图纸号模糊查询"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="定额时间" prop="quotaDt">
        <el-date-picker clearable size="small"
                        v-model="queryParams.quotaDt"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择定额时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
     <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:processExec:add']"
        >新增
        </el-button>
      </el-col>-->
      <!--<el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mes:processExec:edit']"
        >修改
        </el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mes:processExec:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:processExec:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="processExecList" :highlight-current-row="true" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" fixed="left"/>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" class="demo-table-expand">
            <el-form-item label="备注：">
              <span>{{ props.row.actualNote }}</span>
            </el-form-item>
            <el-form-item label="审核人：">
              <span>{{ props.row.confirmUserName }}</span>
            </el-form-item>
            <el-form-item label="审核结果：">
              <dict-tag :options="dict.type.oa_dict_confirm_status" :value="props.row.oaDictConfirmStatus"/>
            </el-form-item>
            <el-form-item label="审核时间：">
              <span>{{ props.row.confirmDt }}</span>
            </el-form-item>
            <el-form-item label="审核意见：">
              <span>{{ props.row.confirmNote }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="投放时间" align="center" prop="execDocDt" width="180"/>
      <el-table-column label="施工号" align="center" prop="docNum" width="150"/>
      <el-table-column label="物料名称" align="center" prop="itemName" width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="物料编码" align="center" prop="itemNum" width="180"/>
      <el-table-column label="规格" align="center" prop="itemSpecification" width="120"/>
      <el-table-column label="数量" align="center" prop="execQty"/>
      <el-table-column label="计量单位" align="center" prop="wmsDictMeasuringUnit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_dict_measuring_unit" :value="scope.row.wmsDictMeasuringUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="开始日期" align="center" prop="docDtStart" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.docDtStart, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="docDtEnd" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.docDtEnd, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="技术员" align="center" prop="processAttentionUserName" width="120"/>
      <el-table-column label="工艺规程" align="center" prop="processDocNum" width="150"/>
      <el-table-column label="任务号" align="center" prop="taskDocNum" width="150"/>
      <el-table-column label="车间" align="center" prop="deptName" width="120"/>
      <el-table-column label="审核状态" align="center" prop="oaDictConfirmStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.oa_dict_confirm_status" :value="scope.row.oaDictConfirmStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="已完成" align="center" prop="sysYesNoDone" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.sysYesNoDone"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
         <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:processExec:edit']"
          >修改
          </el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mes:processExec:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-set-up"
            @click="win_show_details(scope.row)"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-success"
            @click="showDialog_confirm(scope.row)"
            v-hasPermi="['mes:process:remove']"
          >审核
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--
      添加或修改工艺施工对话框
    -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="title" :visible.sync="open" width="850px" append-to-body :close-on-click-modal=false>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <!-- 检索条件 -->
      <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">

        <div slot="header" class="clearfix">
          <span><b>订单信息</b></span>
          <el-tooltip content="显示 / 隐藏" placement="top" style="float: right; padding: 3px 0">
            <el-switch
              v-model="fold_form_order"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="false"
              inactive-value="true">
            </el-switch>
          </el-tooltip>
        </div>

        <div v-show="fold_form_order == 'false'">

            <el-row>
              <el-col :span="24">
                <el-form-item label="订单产品" prop="selectedOrderDetail">
                  <el-input v-model="form.fkOrderDetailUuid" v-show="false"/>
                  <el-input placeholder="请选择订单产品" :style="{width: '100%'}" v-model="form.selectedOrderDetail"
                            class="input-with-select" readonly>
                    <el-button @click="dialog_show_selectOrderDetail" slot="append" icon="el-icon-search"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="订单编号"  size="small" >
                  {{form.o_docNum}}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物料名称"  size="small" >
                  {{form.o_itemName}}
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="订单日期"  size="small" >
                  {{form.o_docDt}}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物料编码"  size="small" >
                  {{form.o_itemNum}}
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="客户名称"  size="small" >
                  {{form.o_custName}}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="订单数量" prop="docNum" size="small" >
                  {{form.o_orderDetailQty}}
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="物料ID" prop="orderDetailItemUuid" v-show="false">
              <el-input v-model="form.fkItemUuid"/>
            </el-form-item>
        </div>

      </el-card>

      <el-row>
        <el-col :span="12">
          <el-form-item prop="versionNum">
            <span slot="label">
                    版本号
                   <el-tooltip content="工艺规程版本号" placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>
            <el-select
              filterable
              v-model="form.fkMesProcessUuid"
              placeholder="请选择版本号"
              clearable
              size="small"
              :style="{width: '100%'}"
            >
              <el-option
                v-for="item in versionNumList"
                :key="item.processUuid"
                :label="item.versionNum"
                :value="item.processUuid"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="单据编号" prop="docNum">
            <el-input v-model="form.docNum"
                      placeholder="请输入单据编号"
                      :style="{width: '100%'}"/>
          </el-form-item>

          <el-form-item label="经办人" prop="fkAttentionUserId">
            <el-input v-model="form.fkAttentionUserId" v-show="false"/>
            <el-input placeholder="请选择经办人" v-model="form.selectedAttentionUser" class="input-with-select">
              <el-button @click="dialog_show_selectUser" :style="{width: '100%'}" slot="append"
                         icon="el-icon-search"></el-button>
            </el-input>
          </el-form-item>

        </el-col>

        <el-col :span="12">

          <el-form-item prop="execQty">
             <span slot="label">
                    数量
                   <el-tooltip content="工艺施工数量" placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>
            <el-input-number v-model="form.execQty" :style="{width: '100%'}" :step="2" placeholder="请输入数量"/>
          </el-form-item>

          <el-form-item label="单据时间" prop="docDt">
            <el-date-picker clearable size="small"
                            v-model="form.docDt"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="选择单据时间"
                            :style="{width: '100%'}">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="状态" prop="sysNormalDisable">
            <el-radio-group v-model="form.sysNormalDisable">
              <el-radio
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>

        </el-col>
      </el-row>

    </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 定额 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="title_quota" :visible.sync="open_quota" width="600px" append-to-body>
      <el-form ref="form_quota" :model="form_quota" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="定额时间" prop="quotaDt">
              <el-date-picker clearable size="small"
                              v-model="form_quota.quotaDt"
                              type="date"
                              value-format="yyyy-MM-dd"
                              style="width: 202px"
                              placeholder="选择定额时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="定额级别" prop="mesDictQuotaLevel">
              <el-select v-model="form_quota.mesDictQuotaLevel" placeholder="请选择定额级别" >
                <el-option
                  v-for="dict in dict.type.mes_dict_quota_level"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位时长"  size="small" >
              <el-input v-model="form_quota.quotaPerMinutes" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总时长"  size="small" >
              <el-input v-model="form_quota.quotaTotalMinutes" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm_quota">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <select-orderDetail ref="component_selectOrderDetail" @ok="selectOrderDetail_done"/>
    <select-user ref="component_selectUser" :roleId="queryParams.roleId" @ok="selectUser_done"/>
    <confirm ref="component_confirm"  @ok="confirm_done" />
  </div>
</template>

<script>
import {
  listProcessExec,
  getProcessExec,
  delProcessExec,
  addProcessExec,
  updateProcessExec, genProcessExec
} from "@/api/mes/processExec";
  import{newDocNum} from "@/api/oa/docNum";
  import selectOrderDetail from "../../crm/crmOrders/selectOrderDetail";
  import {listProcess} from "@/api/mes/process";
  import selectUser from "../../system/user/selectUser";
  import confirm from "../../oa/confirm";
import {listTasks} from "@/api/mes/tasks";
  export default {
    name: "ProcessExec",
    components: { selectOrderDetail,selectUser,confirm },
    dicts: ['sys_normal_disable','oa_dict_confirm_status','mes_dict_quota_level','sys_yes_no','wms_dict_measuring_unit'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,

        versionNumList: [],
        // 总条数
        total: 0,
        // 工艺施工表格数据
        processExecList: [],
        tasksList:[],
        fold_form_order: 'false',
        // 弹出层标题
        title: "",
        title_quota: "",
        // 是否显示弹出层
        open: false,
        open_quota: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          fkMesProcessUuid: null,
          fkOrderDetailUuid: null,
          parentUuid: null,
          ancestors: null,
          versionNum: null,
          drawNum: null,
          fkItemUuid: null,
          orderNum: null,
          sysDictLevelGenPs: null,
          sysYesNoDone: null,
          quotaDt: null,
          mesDictQuotaLevel: null,
          quotaPerMinutes: null,
          quotaTotalMinutes: null,
          execQty: null,
          wmsDictMeasuringUnit: null,
          sysNormalDisable: null,
          docTitle: null,
          docNum: null,
          docDt: null,
          docNote: null,
          fkAttentionUserId: null,
          fkConfirmUserId: null,
          confirmDt: null,
          oaDictConfirmStatus: null,
          confirmNote: null,
          execFkConfirmUserId: null,
          execComfirmDt: null,
          execOaDictConfirmStatus: null,
          execConfirmNote: null,
          orderDetailItemUuid: null,
        },
        // 表单参数
        form: {
          versionNum: '',
        },
        form_order: {}, // 表单：订单
        form_quota: {},
        // 表单校验
        rules: {
          fkMesProcessUuid: [
            {required: true, message: "工艺规程ID不能为空", trigger: "blur"}
          ],
          fkOrderDetailUuid: [
            {required: true, message: "订单明细ID不能为空", trigger: "blur"}
          ],
          parentUuid: [
            {required: true, message: "父ID不能为空", trigger: "blur"}
          ],
          fkItemUuid: [
            {required: true, message: "物品表ID不能为空", trigger: "blur"}
          ],
          sysDictLevelGenPs: [
            {required: true, message: "生成生产计划的级别不能为空", trigger: "blur"}
          ],
          sysYesNoDone: [
            {required: true, message: "是否完工不能为空", trigger: "blur"}
          ],
          oaDictConfirmStatus: [
            {required: true, message: "审核状态不能为空", trigger: "blur"}
          ],
          createBy: [
            {required: true, message: "创建者不能为空", trigger: "blur"}
          ],
          createTime: [
            {required: true, message: "创建时间不能为空", trigger: "blur"}
          ],
        }
      };
    },
    created() {
      this.getList();
      this.getProcessExec();
    },
    methods: {
      /** 打开对话框：审核 */
      showDialog_confirm(row) {
        console.log(row)
        let obj = {
          tableName: 'mes_process_exec',
          uuidColumn: 'process_exec_uuid',
          fkUuid: row.processExecUuid,
          attentionUserNickName: row.processAttentionUserName,
          oaDictConfirmStatus: row.oaDictConfirmStatus,
          msg: `请审核工艺施工, 施工号：${row.docNum}`
        }
        this.$refs.component_confirm.showDialog_confirm(obj);

      },

      confirm_done() {
        this.getList()
      },

      /** 查询工艺施工列表 */
      getList() {
        this.loading = true;
        this.queryParams.parentUuid=0
        listProcessExec(this.queryParams).then(response => {
          this.processExecList = response.rows;
          this.total = response.total;
          this.loading = false;
        });

      },

      getProcessExec() {
        listTasks(this.queryParams).then(response => {
          this.tasksList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
    },

      /** 获取工艺规程的版本号 */
      getList_versionNum(itemUuid) {
        let param = {
          fkItemUuid: itemUuid,
          parentUuid: 0,
          oaDictConfirmStatus: 'pass',
        }
        listProcess(param).then( response => {
          this.versionNumList = response.rows;
          this.form.fkMesProcessUuid = response.rows[0].processUuid // 选中下拉列表中的第一项
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          processExecUuid: null,
          fkMesProcessUuid: null,
          fkOrderDetailUuid: null,
          parentUuid: null,
          ancestors: null,
          versionNum: null,
          drawNum: null,
          fkItemUuid: null,
          orderNum: null,
          sysDictLevelGenPs: null,
          sysYesNoDone: null,
          quotaDt: null,
          mesDictQuotaLevel: null,
          quotaPerMinutes: null,
          quotaTotalMinutes: null,
          execQty: null,
          wmsDictMeasuringUnit: null,
          sysNormalDisable: '0', // 正常
          docTitle: null,
          docNum: null,
          docDt: null,
          docNote: null,
          fkAttentionUserId: null,
          fkConfirmUserId: null,
          confirmDt: null,
          oaDictConfirmStatus: "0",
          confirmNote: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          orderDetailItemUuid: null,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 多选框选中数据 */
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.processExecUuid)
        this.docNums = selection.map(item => item.docNum)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();

        newDocNum({preCode:'EXE-', len: 12}).then(response => {
          this.form.docNum = response.msg
        })

        this.open = true;
        this.title = "添加工艺施工";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const processExecUuid = row.processExecUuid || this.ids
        getProcessExec(processExecUuid).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改工艺施工";
        });
      },


      /** 修改按钮操作 */
      showDialog_quota(row) {
        this.reset();
        const processExecUuid = row.processExecUuid || this.ids
        getProcessExec(processExecUuid).then(response => {
          this.form_quota = response.data;
          this.open_quota = true;
          this.title_quota = "定额";
        });
      },


      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.processExecUuid != null) {
              updateProcessExec(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              genProcessExec(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      submitForm_quota() {
        this.$refs["form_quota"].validate(valid => {
          if (valid) {
            if (this.form_quota.processExecUuid != null) {
              updateProcessExec(this.form_quota).then(response => {
                this.$modal.msgSuccess("定额成功");
                this.open_quota = false;
                this.getList();
              });
            } else {
              addProcessExec(this.form_quota).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open_quota = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const processExecUuids = row.processExecUuid || this.ids;
        const docNums = row.docNum || this.docNums;
        this.$modal.confirm('是否确认删除施工号为"' + docNums + '"的数据项？').then(function () {
          return delProcessExec(processExecUuids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('mes/processExec/export', {
          ...this.queryParams
        }, `mes_processExec.xlsx`)
      },
      /** 显示对话框：选择订单 */
      dialog_show_selectOrderDetail() {
        this.$refs.component_selectOrderDetail.dialog_show_selectOrderDetail();
      },


      /** 选择订单明细完成 */
      selectOrderDetail_done(user) {
        console.log(user)
        this.form.fkOrderDetailUuid = user.row.orderDetailUuid;
        this.form.selectedOrderDetail =
          `物料名称：${user.row.itemName}，物料编码：${user.row.itemNum}`;
        this.form.selectOrderDetail = `物料名称：${user.row.itemName}，物料编码：${user.row.itemNum}`;
        this.form.o_docNum = user.row.docNum;
        this.form.o_itemName = user.row.itemName;
        this.form.o_docDt = user.row.docDt;
        this.form.o_itemNum = user.row.itemNum;
        this.form.o_custName = user.row.custName;
        this.form.o_orderDetailQty = user.row.orderDetailQty;
        this.form.fkItemUuid = user.row.orderDetailItemUuid;
        this.getList_versionNum(this.form.fkItemUuid)

      },

      // 窗口：显示 - 查看详情
      win_show_details(r) {
        console.log(r.processExecUuid)
        this.$router.push(`/mes/processExec-details/${r.processExecUuid}`);
      },

      /** 打开授权用户表弹窗 */
      dialog_show_selectUser() {
        this.$refs.component_selectUser.show();
      },

      /** 选择用户完成 */
      selectUser_done(user) {
        console.log(user)
        this.form.fkAttentionUserId = user.userId
        this.form.selectedAttentionUser = `${user.nickName}（用户名：${user.userName}，ID：${user.userId}）`
      },
    }
  };
</script>
